<!--
 * @Description: 描述信息
 * @Version: 版本号
 * @Author: xuebao
 * @Date: 2023-12-04 20:07:41
 * @LastEditors: renmengxue
 * @LastEditTime: 2023-12-05 11:11:52
-->
<template>
  <form class="validate-form-container">
    <slot></slot>
    <div class="submit-area" @click.prevent="submitForm">
      <slot name="submit">
        <button class="btn btn-primary">提交</button>
      </slot>
    </div>
  </form>
</template>

<script lang="ts">
import { defineComponent, onUnmounted } from 'vue'
// 现在mitt要求每个事件名称和事件类型要一一对应
import mitt from 'mitt'
type ValidateFunc = () => boolean
type Events = { 'form-item-created': ValidateFunc }// 定义一个Event类型  这个对应是让事件和对应的callback 一一对应
export const emitter = mitt<Events>()// 实例化 mitt 的时候，作为泛型传递进去
export default defineComponent({
  emits: ['form-submit'],
  setup(props, context) {
    let funcArr: ValidateFunc[] = []// 里面装的是一堆函数返回的是boolean值
    const submitForm = () => {
      // some every  数组的方法会提前停止循环，every如果遇到false的话就会出现false
      const result = funcArr.map(func => func()).every(result => result)
      console.log(result, 'resize')

      context.emit('form-submit', result)
    }
    const callback = (func: ValidateFunc) => {
      funcArr.push(func)
    }
    // 注册一个方法
    emitter.on('form-item-created', callback)
    onUnmounted(() => {
      emitter.off('form-item-created', callback)
      funcArr = []// 清空数组
    })
    return {
      submitForm
    }
  }
})
</script>

<style scoped></style>
